{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Building the Streaming Dataflow Accelerator\n",
    "\n",
    "<font color=\"red\">**Live FINN tutorial:** We recommend clicking **Cell -> Run All** when you start reading this notebook for \"latency hiding\".</font>\n",
    "\n",
    "**Important: This notebook depends on the 1-train-mlp-with-brevitas notebook because we are using models that were created by that notebook. So please make sure the needed .onnx files are generated prior to running this notebook.**\n",
    "\n",
    "<img align=\"left\" src=\"finn-example.png\" alt=\"drawing\" style=\"margin-right: 20px\" width=\"250\"/>\n",
    "\n",
    "In this notebook, we'll use the FINN compiler generate an FPGA accelerator with a streaming dataflow architecture from our quantized MLP for the cybersecurity task. The key idea in such architectures is to parallelize across layers as well as within layers by dedicating a proportionate amount of compute resources to each layer, illustrated on the figure to the left. You can read more about the general concept in the [FINN](https://arxiv.org/pdf/1612.07119) and [FINN-R](https://dl.acm.org/doi/pdf/10.1145/3242897) papers. This is done by mapping each layer to a Vivado HLS description, parallelizing each layer's implementation to the appropriate degree and using on-chip FIFOs to link up the layers to create the full accelerator.\n",
    "\n",
    "These implementations offer a good balance of performance and flexibility, but building them by hand is difficult and time-consuming. This is where the FINN compiler comes in: it can build streaming dataflow accelerators from an ONNX description to match the desired throughput."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Outline\n",
    "-------------\n",
    "\n",
    "1. [Introduction to  `build_dataflow` Tool](#intro_build_dataflow) \n",
    "2. [Understanding the Build Configuration: `DataflowBuildConfig`](#underst_build_conf)     \n",
    "    2.1.[Output Products](#output_prod)   \n",
    "    2.2.[Configuring the Board and FPGA Part](#config_fpga)   \n",
    "    2.3 [Configuring the Performance](#config_perf)    \n",
    "4. [Launch a Build: Only Estimate Reports](#build_estimate_report)\n",
    "5. [Launch a Build: Stitched IP, out-of-context synth and rtlsim Performance](#build_ip_synth_rtlsim)\n",
    "6. [(Optional) Launch a Build: PYNQ Bitfile and Driver](#build_bitfile_driver)\n",
    "7. [(Optional) Run on PYNQ board](#run_on_pynq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to  `build_dataflow` Tool <a id=\"intro_build_dataflow\"></a>\n",
    "\n",
    "Since version 0.5b, the FINN compiler has a `build_dataflow` tool. Compared to previous versions which required setting up all the needed transformations in a Python script, it makes experimenting with dataflow architecture generation easier. The core idea is to specify the relevant build info as a configuration `dict`, which invokes all the necessary steps to make the dataflow build happen. It can be invoked either from the [command line](https://finn-dev.readthedocs.io/en/latest/command_line.html) or with a single Python function call.\n",
    "\n",
    "\n",
    "In this notebook, we'll use the Python function call to invoke the builds to stay inside the Jupyter notebook, but feel free to experiment with reproducing what we do here with the `./run-docker.sh build_dataflow` and `./run-docker.sh build_custom` command-line entry points too. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Understanding the Build Configuration: `DataflowBuildConfig` <a id=\"underst_build_conf\"></a>\n",
    "\n",
    "The build configuration is specified by an instance of `finn.builder.build_dataflow_config.DataflowBuildConfig`. The configuration is a Python [`dataclass`](https://docs.python.org/3/library/dataclasses.html) which can be serialized into or de-serialized from JSON files for persistence, although we'll just set it up in Python here.\n",
    "There are many options in the configuration to customize different aspects of the build, we'll only cover a few of them in this notebook. You can read the details on all the config options on [the FINN API documentation](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.DataflowBuildConfig).\n",
    "\n",
    "Let's go over some of the members of the `DataflowBuildConfig`:\n",
    "\n",
    "### Output Products <a id=\"output_prod\"></a>\n",
    "\n",
    "The build can produce many different outputs, and some of them can take a long time (e.g. bitfile synthesis for a large network). When you first start working on generating a new accelerator and exploring the different performance options, you may not want to go all the way to a bitfile. Thus, in the beginning you may just select the estimate reports as the output products. Gradually, you can generate the output products from later stages until you are happy enough with the design to build the full accelerator integrated into a shell.\n",
    "\n",
    "The output products are controlled by:\n",
    "\n",
    "* `generate_outputs`: list of output products (of type [`finn.builder.build_dataflow_config.DataflowOutputType`](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.DataflowOutputType)) that will be generated by the build. Some available options are:\n",
    "    - `ESTIMATE_REPORTS` : report expected resources and performance per layer and for the whole network without any synthesis\n",
    "    - `STITCHED_IP` : create a stream-in stream-out IP design that can be integrated into other Vivado IPI or RTL designs\n",
    "    - `RTLSIM_PERFORMANCE` : use PyVerilator to do a performance/latency test of the `STITCHED_IP` design\n",
    "    - `OOC_SYNTH` : run out-of-context synthesis (just the accelerator itself, without any system surrounding it) on the `STITCHED_IP` design to get post-synthesis FPGA resources and achievable clock frequency\n",
    "    - `BITFILE` : integrate the accelerator into a shell to produce a standalone bitfile\n",
    "    - `PYNQ_DRIVER` : generate a PYNQ Python driver that can be used to launch the accelerator\n",
    "    - `DEPLOYMENT_PACKAGE` : create a folder with the `BITFILE` and `PYNQ_DRIVER` outputs, ready to be copied to the target FPGA platform.\n",
    "* `output_dir`: the directory where all the generated build outputs above will be written into.\n",
    "* `steps`: list of predefined (or custom) build steps FINN will go through. Use `build_dataflow_config.estimate_only_dataflow_steps` to execute only the steps needed for estimation (without any synthesis), and the `build_dataflow_config.default_build_dataflow_steps` otherwise (which is the default value). You can find the list of default steps [here](https://finn.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.default_build_dataflow_steps) in the documentation.\n",
    "\n",
    "### Configuring the Board and FPGA Part <a id=\"config_fpga\"></a>\n",
    "\n",
    "* `fpga_part`: Xilinx FPGA part to be used for synthesis, can be left unspecified to be inferred from `board` below, or specified explicitly for e.g. out-of-context synthesis.\n",
    "* `board`: target Xilinx Zynq or Alveo board for generating accelerators integrated into a shell. See the `pynq_part_map` and `alveo_part_map` dicts in [this file](https://github.com/Xilinx/finn-base/blob/dev/src/finn/util/basic.py#L41) for a list of possible boards.\n",
    "* `shell_flow_type`: the target [shell flow type](https://finn-dev.readthedocs.io/en/latest/source_code/finn.builder.html#finn.builder.build_dataflow_config.ShellFlowType), only needed for generating full bitfiles where the FINN design is integrated into a shell (so only needed if `BITFILE` is selected) \n",
    "\n",
    "### Configuring the Performance <a id=\"config_perf\"></a>\n",
    "\n",
    "You can configure the performance (and correspondingly, the FPGA resource footprint) of the generated dataflow accelerator in two ways:\n",
    "\n",
    "1) (basic) Set a target performance and let the compiler figure out the per-node parallelization settings.\n",
    "\n",
    "2) (advanced) Specify a separate .json as `folding_config_file` that lists the degree of parallelization (as well as other hardware options) for each layer.\n",
    "\n",
    "This notebook only deals with the basic approach, for which you need to set up:\n",
    "\n",
    "* `target_fps`: target inference performance in frames per second. Note that target may not be achievable due to specific layer constraints, or due to resource limitations of the FPGA. \n",
    "* `synth_clk_period_ns`: target clock frequency (in nanoseconds) for Vivado synthesis. e.g. `synth_clk_period_ns=5.0` will target a 200 MHz clock. Note that the target clock period may not be achievable depending on the FPGA part and design complexity."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch a Build: Only Estimate Reports <a id=\"build_estimate_report\"></a>\n",
    "\n",
    "First, we'll launch a build that only generates the estimate reports, which does not require any synthesis. Note two things below: how the `generate_outputs` only contains `ESTIMATE_REPORTS`, but also how the `steps` uses a value of `estimate_only_dataflow_steps`. This skips steps like HLS synthesis to provide a quick estimate from analytical models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import finn.builder.build_dataflow as build\n",
    "import finn.builder.build_dataflow_config as build_cfg\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "model_file = \"cybsec-mlp-ready.onnx\"\n",
    "\n",
    "estimates_output_dir = \"output_estimates_only\"\n",
    "\n",
    "#Delete previous run results if exist\n",
    "if os.path.exists(estimates_output_dir):\n",
    "    shutil.rmtree(estimates_output_dir)\n",
    "    print(\"Previous run results deleted!\")\n",
    "\n",
    "\n",
    "cfg_estimates = build.DataflowBuildConfig(\n",
    "    output_dir          = estimates_output_dir,\n",
    "    mvau_wwidth_max     = 80,\n",
    "    target_fps          = 1000000,\n",
    "    synth_clk_period_ns = 10.0,\n",
    "    fpga_part           = \"xc7z020clg400-1\",\n",
    "    steps               = build_cfg.estimate_only_dataflow_steps,\n",
    "    generate_outputs=[\n",
    "        build_cfg.DataflowOutputType.ESTIMATE_REPORTS,\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "build.build_dataflow_cfg(model_file, cfg_estimates)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll now examine the generated outputs from this build. If we look under the outputs directory, we'll find a subfolder with the generated estimate reports."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! ls {estimates_output_dir}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! ls {estimates_output_dir}/report"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that various reports have been generated as .json files. Let's examine the contents of the `estimate_network_performance.json` for starters. Here, we can see the analytical estimates for the performance and latency."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! cat {estimates_output_dir}/report/estimate_network_performance.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since all of these reports are .json files, we can easily load them into Python for further processing. This can be useful if you are building your own design automation tools on top of FINN. Let's define a helper function and look at the `estimate_layer_cycles.json` report."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "def read_json_dict(filename):\n",
    "    with open(filename, \"r\") as f:\n",
    "        ret = json.load(f)\n",
    "    return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "read_json_dict(estimates_output_dir + \"/report/estimate_layer_cycles.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, we can see the estimated number of clock cycles each layer will take. Recall that all of these layers will be running in parallel, and the slowest layer will determine the overall throughput of the entire neural network. FINN attempts to parallelize each layer such that they all take a similar number of cycles, and less than the corresponding number of cycles that would be required to meet `target_fps`. Additionally by summing up all layer cycle estimates one can obtain an estimate for the overall latency of the whole network. \n",
    "\n",
    "Finally, we can see the layer-by-layer resource estimates in the `estimate_layer_resources.json` report:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "read_json_dict(estimates_output_dir + \"/report/estimate_layer_resources.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This particular report is useful to determine whether the current configuration will fit into a particular FPGA. If you see that the resource requirements are too high for the FPGA you had in mind, you should consider lowering the `target_fps`.\n",
    "\n",
    "**Note that the analytical models tend to over-estimate how much resources are needed, since they can't capture the effects of various synthesis optimizations.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch a Build: Stitched IP, out-of-context synth and rtlsim Performance <a id=\"build_ip_synth_rtlsim\"></a>\n",
    "\n",
    "Once we have a configuration that gives satisfactory estimates, we can move on to generating the accelerator. We can do this in different ways depending on how we want to integrate the accelerator into a larger system. For instance, if we have a larger streaming system built in Vivado or if we'd like to re-use this generated accelerator as an IP component in other projects, the `STITCHED_IP` output product is a good choice. We can also use the `OOC_SYNTH` output product to get post-synthesis resource and clock frequency numbers for our accelerator.\n",
    "\n",
    "<font color=\"red\">**Live FINN tutorial:** These next builds will take about 10 minutes to complete since multiple calls to Vivado and a call to RTL simulation are involved. While this is running, you can examine the generated files with noVNC -- it is running on **(your AWS URL):6080/vnc.html**\n",
    "\n",
    "* Once the `step_hls_codegen [8/16]` below is completed, you can view the generated HLS code under its own folder for each layer: `/tmp/finn_dev_ubuntu/code_gen_ipgen_MatrixVectorActivation_XXXXXX`\n",
    "    \n",
    "* Once the `step_create_stitched_ip [11/16]` below is completed, you can view the generated stitched IP in Vivado under `/home/ubuntu/finn/notebooks/end2end_example/cybersecurity/output_ipstitch_ooc_rtlsim/stitched_ip`\n",
    "</font> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import finn.builder.build_dataflow as build\n",
    "import finn.builder.build_dataflow_config as build_cfg\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "model_file = \"cybsec-mlp-ready.onnx\"\n",
    "\n",
    "rtlsim_output_dir = \"output_ipstitch_ooc_rtlsim\"\n",
    "\n",
    "#Delete previous run results if exist\n",
    "if os.path.exists(rtlsim_output_dir):\n",
    "    shutil.rmtree(rtlsim_output_dir)\n",
    "    print(\"Previous run results deleted!\")\n",
    "\n",
    "cfg_stitched_ip = build.DataflowBuildConfig(\n",
    "    output_dir          = rtlsim_output_dir,\n",
    "    mvau_wwidth_max     = 80,\n",
    "    target_fps          = 1000000,\n",
    "    synth_clk_period_ns = 10.0,\n",
    "    fpga_part           = \"xc7z020clg400-1\",\n",
    "    generate_outputs=[\n",
    "        build_cfg.DataflowOutputType.STITCHED_IP,\n",
    "        build_cfg.DataflowOutputType.RTLSIM_PERFORMANCE,\n",
    "        build_cfg.DataflowOutputType.OOC_SYNTH,\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "build.build_dataflow_cfg(model_file, cfg_stitched_ip)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why is e.g. `step_synthesize_bitfile` listed above even though we didn't ask for a bitfile in the output products? This is because we're using the default set of build steps, which includes `step_synthesize_bitfile`. Since its output product is not selected, this step will do nothing."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Among the output products, we will find the accelerator exported as a stitched IP block design:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! ls {rtlsim_output_dir}/stitched_ip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We also have a few reports generated by these output products, different from the ones generated by `ESTIMATE_REPORTS`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! ls {rtlsim_output_dir}/report"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In `ooc_synth_and_timing.json` we can find the post-synthesis and maximum clock frequency estimate for the accelerator. Note that the clock frequency estimate here tends to be optimistic, since out-of-context synthesis is less constrained."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! cat {rtlsim_output_dir}/report/ooc_synth_and_timing.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In `rtlsim_performance.json` we can find the steady-state throughput and latency for the accelerator, as obtained by rtlsim. If the DRAM bandwidth numbers reported here are below what the hardware platform is capable of (i.e. the accelerator is not memory-bound), you can expect the same steady-state throughput (excluding any software/driver overheads) in real hardware."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! cat {rtlsim_output_dir}/report/rtlsim_performance.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, let's have a look at `final_hw_config.json`. This is the node-by-node hardware configuration determined by the FINN compiler, including FIFO depths, parallelization settings (PE/SIMD) and others. If you want to optimize your build further (the \"advanced\" method we mentioned under \"Configuring the performance\"), you can use this .json file as the `folding_config_file` for a new run to use it as a starting point for further exploration and optimizations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! cat {rtlsim_output_dir}/final_hw_config.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## (Optional) Launch a Build: PYNQ Bitfile and Driver <a id=\"build_bitfile_driver\"></a>\n",
    "\n",
    "<font color=\"red\">**Live FINN tutorial:** This section is not included in the hands-on tutorial due to the bitfile synthesis time (15-20 min). If you own a PYNQ board, we encourage you to uncomment the cells below to try it out on your own after the tutorial.</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import finn.builder.build_dataflow as build\n",
    "import finn.builder.build_dataflow_config as build_cfg\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "model_file = \"cybsec-mlp-ready.onnx\"\n",
    "\n",
    "final_output_dir = \"output_final\"\n",
    "\n",
    "#Delete previous run results if exist\n",
    "if os.path.exists(final_output_dir):\n",
    "    shutil.rmtree(final_output_dir)\n",
    "    print(\"Previous run results deleted!\")\n",
    "\n",
    "cfg = build.DataflowBuildConfig(\n",
    "    output_dir          = final_output_dir,\n",
    "    mvau_wwidth_max     = 80,\n",
    "    target_fps          = 1000000,\n",
    "    synth_clk_period_ns = 10.0,\n",
    "    board               = \"Pynq-Z1\",\n",
    "    shell_flow_type     = build_cfg.ShellFlowType.VIVADO_ZYNQ,\n",
    "    generate_outputs=[\n",
    "        build_cfg.DataflowOutputType.BITFILE,\n",
    "        build_cfg.DataflowOutputType.PYNQ_DRIVER,\n",
    "        build_cfg.DataflowOutputType.DEPLOYMENT_PACKAGE,\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%time\n",
    "#build.build_dataflow_cfg(model_file, cfg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For our final build, the output products include the bitfile (and the accompanying .hwh file, also needed to execute correctly on PYNQ for Zynq platforms):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! ls {final_output_dir}/bitfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The generated Python driver lets us execute the accelerator on PYNQ platforms with simply numpy i/o. You can find some notebooks showing how to use FINN-generated accelerators at runtime in the [finn-examples](https://github.com/Xilinx/finn-examples) repository."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! ls {final_output_dir}/driver"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The reports folder contains the post-synthesis resource and timing reports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! ls {final_output_dir}/report"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we have the `deploy` folder which contains everything you need to copy onto the target board to get the accelerator running:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! ls {final_output_dir}/deploy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## (Optional) Run on PYNQ board <a id=\"run_on_pynq\"></a>\n",
    "\n",
    "<font color=\"red\">**Live FINN tutorial:** This section is not included in the hands-on tutorial due to the bitfile synthesis time (15-20 min) of the previous section. If you own a PYNQ board, we encourage you to uncomment the cells below to try it out on your own after the tutorial.</font>\n",
    "\n",
    "To test the accelerator on the board, we'll put a copy of the dataset and a premade Python script that validates the accuracy into the `driver` folder, then make a zip archive of the whole deployment folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! cp unsw_nb15_binarized.npz {final_output_dir}/deploy/driver"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! cp validate-unsw-nb15.py {final_output_dir}/deploy/driver"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#! ls {final_output_dir}/deploy/driver"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#from shutil import make_archive\n",
    "#make_archive('deploy-on-pynq', 'zip', final_output_dir+\"/deploy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can now download the created zipfile (**File -> Open**, mark the checkbox next to the `deploy-on-pynq.zip` and select Download from the toolbar), then copy it to your PYNQ board (for instance via `scp` or `rsync`). Then, run the following commands **on the PYNQ board** to extract the archive and run the validation:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```shell\n",
    "unzip deploy-on-pynq.zip -d finn-cybsec-mlp-demo\n",
    "cd finn-cybsec-mlp-demo/driver\n",
    "sudo python3.6 -m pip install bitstring\n",
    "sudo python3.6 validate-unsw-nb15.py --batchsize 1000\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should see `Final accuracy: 91.868293` at the end. You may have noticed that the validation doesn't *quite* run at 1M inferences per second. This is because of the Python packing/unpacking and data movement overheads. To see this in more detail, the generated driver includes a benchmarking mode that shows the runtime breakdown:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```shell\n",
    "sudo python3.6 driver.py --exec_mode throughput_test --bitfile ../bitfile/finn-accel.bit --batchsize 1000\n",
    "cat nw_metrics.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{'runtime[ms]': 1.0602474212646484,\n",
    " 'throughput[images/s]': 943176.0737575893,\n",
    " 'DRAM_in_bandwidth[Mb/s]': 70.7382055318192,\n",
    " 'DRAM_out_bandwidth[Mb/s]': 0.9431760737575894,\n",
    " 'fclk[mhz]': 100.0,\n",
    " 'batch_size': 1000,\n",
    " 'fold_input[ms]': 9.679794311523438e-05,\n",
    " 'pack_input[ms]': 0.060115814208984375,\n",
    " 'copy_input_data_to_device[ms]': 0.002428770065307617,\n",
    " 'copy_output_data_from_device[ms]': 0.0005249977111816406,\n",
    " 'unpack_output[ms]': 0.3773000240325928,\n",
    " 'unfold_output[ms]': 6.818771362304688e-05}```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, the various `pack_input/unpack_output` calls show the overhead of packing/unpacking the inputs/outputs to convert from numpy arrays to the bit-contiguous data representation our accelerator expects. The `copy_input_data_to_device` and `copy_output_data_from_device` indicate the cost of moving the data between the CPU and accelerator memories. These overheads can dominate the execution time when running with small batch sizes.\n",
    "\n",
    "Finally, we can see that `throughput[images/s]`, which is the pure hardware throughput without any software and data movement overheads, is close to 1M inferences per second."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
